package com.moyun.zbmy.zizhou.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.gridsum.videotracker.entity.VideoInfo;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.moyun.zbmy.zizhou.R;
import com.moyun.zbmy.zizhou.application.Cache;
import com.moyun.zbmy.zizhou.application.Constances;
import com.moyun.zbmy.zizhou.base.BaseActivity;
import com.moyun.zbmy.zizhou.base.BaseCanPlayActivity;
import com.moyun.zbmy.zizhou.beans.FProgram;
import com.moyun.zbmy.zizhou.beans.LookBackBean;
import com.moyun.zbmy.zizhou.http.AbsListNetCallback;
import com.moyun.zbmy.zizhou.http.NetUtils;
import com.moyun.zbmy.zizhou.ui.adapter.LookBackNewsAdapter;
import com.moyun.zbmy.zizhou.ui.adapter.holder.LookBackNewsHolder;
import com.moyun.zbmy.zizhou.ui.adapter.holder.OnlyTitleHolder;
import com.moyun.zbmy.zizhou.ui.utils.SkipUtil;
import com.moyun.zbmy.zizhou.ui.utils.TitleUtils;
import com.moyun.zbmy.zizhou.ui.widget.BasePlayerView;
import com.moyun.zbmy.zizhou.utils.ListTypeUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LookBackNewsActivity extends BaseCanPlayActivity implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener
        , LookBackNewsHolder.OnColumnItemClickListener, LookBackNewsHolder.OnColumnClickListener, BaseCanPlayActivity.OnPlayerFullClickListener {
    @BindView(R.id.fm_live_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView recyclerView;
    @BindView(R.id.title_top_layout_edit)
    protected CustomFontTextView share;
    private Handler handler;
    private List<LookBackBean> lookBackList = new ArrayList<>();
    private LookBackNewsAdapter adapter;
    private BasePlayerView playPlayer = null;
    private int lastPlayIndex = 0;
    private int topPosition;
    private int bottomPosition;
    private LookBackNewsHolder playHolder = null;
    private int playTemp = -1;
    private String playBackUrl;
    //目标项是否在最后一个可见项之后
    private boolean mShouldScroll;
    //记录目标项位置
    private int mToPosition;
    private boolean isNotScrolled = false;
    private boolean isNotScrollStateChanged = false;

    private int recyclerViewBottom = 0;
    private int currentPage = 0;
    private int pageAll = 0;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        share.setVisibility(View.GONE);
        playBackUrl = getIntent().getStringExtra(BaseActivity.EX_URL);
        handler = new Handler();
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
//        refreshLayout.setLoadMoreEnabled(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        adapter = new LookBackNewsAdapter(this, null, this, this);
        recyclerView.setAdapter(adapter);
        adapter.setActivity(this);
        refreshLayout.autoRefresh();
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            boolean isUp = false;


            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (mShouldScroll && RecyclerView.SCROLL_STATE_IDLE == newState) {
                    mShouldScroll = false;
                    smoothMoveToPosition(recyclerView, mToPosition);
                }
                if (isNotScrollStateChanged) {
//                    isNotScrollStateChanged = false;
                    return;
                }
                if (recyclerView.getLayoutManager() != null && newState == 0) {//滑动停止
                    LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                    topPosition = layoutManager.findFirstVisibleItemPosition();
                    bottomPosition = layoutManager.findLastVisibleItemPosition();
                    playTemp = -1;
                    final RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
                    View topView = layoutManager.findViewByPosition(topPosition);
                    if (null != topView) {
                        int bottom = topView.getBottom();
                        int height = topView.getHeight();
                        if (recyclerView.getChildViewHolder(topView) instanceof OnlyTitleHolder) {
                            topView = layoutManager.findViewByPosition(topPosition + 1);
                            bottom = topView.getBottom();
                            height = topView.getHeight();
                            if (bottom < height / 2) {
                                View view = manager.findViewByPosition(topPosition + 2);
                                if (null != view && recyclerView.getChildViewHolder(view) instanceof LookBackNewsHolder) {
                                    playHolder = (LookBackNewsHolder) recyclerView.getChildViewHolder(view);
                                    playTemp = topPosition + 1;
                                }

                            } else {
                                View view = manager.findViewByPosition(topPosition + 1);
                                if (null != view && recyclerView.getChildViewHolder(view) instanceof LookBackNewsHolder) {
                                    playHolder = (LookBackNewsHolder) recyclerView.getChildViewHolder(view);
                                    playTemp = topPosition + 1;
                                }
                            }
                        } else {
                            if (bottom < height / 2) {
                                View view = manager.findViewByPosition(topPosition + 1);
                                if (null != view && recyclerView.getChildViewHolder(view) instanceof LookBackNewsHolder) {
                                    playHolder = (LookBackNewsHolder) recyclerView.getChildViewHolder(view);
                                    playTemp = topPosition + 1;
                                }

                            } else {
                                View view = manager.findViewByPosition(topPosition);
                                if (null != view && recyclerView.getChildViewHolder(view) instanceof LookBackNewsHolder) {
                                    playHolder = (LookBackNewsHolder) recyclerView.getChildViewHolder(view);
                                    playTemp = topPosition;
                                }

                            }
                        }
                    }
                    if (playTemp != lastPlayIndex) {
                        if (null != playHolder) {
                            View lastView = manager.findViewByPosition(lastPlayIndex);
                        }
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (isNotScrolled) {
                    //点击视频时，不触发此处的处理逻辑
                    return;
                }
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();

                View playingView = layoutManager.findViewByPosition(lastPlayIndex);
                if (null != playingView) {
                    if (recyclerView.getChildViewHolder(playingView) instanceof LookBackNewsHolder) {
                        recyclerViewBottom = recyclerView.getBottom();
                        int top = playingView.getTop();
                        int bottom = playingView.getBottom();
                        int height = playingView.getHeight();
                        boolean isShouldStop = false;
                        if (dy > 0) {
                            if (bottom < height / 2) {
                                isShouldStop = true;
                            }
                        } else {
                            if ((recyclerViewBottom - top) < height / 3) {
                                isShouldStop = true;
                            }
                        }
                        if (isShouldStop) {
                            LookBackNewsHolder lastHolder = (LookBackNewsHolder) recyclerView.getChildViewHolder(playingView);
                            lastHolder.pauseVideo();
                            lastPlayIndex = -1;
                        }
                    }
                }
            }

        });
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_lookback_new);
        ButterKnife.bind(this);
    }


    @Override
    public void onLoadMore() {
        currentPage++;
        getData();
    }

    @Override
    public void onRefresh() {
        if(null!= willHolder){
            willHolder.pauseVideo();
        }
        currentPage = 0;
        getData();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        View lastView = manager.findViewByPosition(lastPlayIndex);
        if (null != lastView && recyclerView.getChildViewHolder(lastView) instanceof LookBackNewsHolder) {
            LookBackNewsHolder lastHolder = (LookBackNewsHolder) recyclerView.getChildViewHolder(lastView);
            lastHolder.pauseVideo();
        }
    }

    /**
     * 获取栏目数据
     */
    private void getData() {
        if (TextUtils.isEmpty(playBackUrl)) {
            toast("数据错误");
            if (currentPage > 0) {
                currentPage--;
            }
            return;
        }
        NetUtils.getNetAdapter().getLookBackNewsProgramList(getOwnerName(), playBackUrl, currentPage, new AbsListNetCallback<LookBackBean>(ListTypeUtils.LookBackBean()) {
            @Override
            public void onSuc(List<LookBackBean> list) {
                if (ListUtils.isListValued(list)) {
                    if (currentPage == 0) {
                        lookBackList.clear();
                        adapter.setData(list);
                    } else {
                        adapter.addData(list);
                    }
                    lookBackList.addAll(list);
//                    adapter.notifyDataSetChanged();
                }

            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                currentPage--;
            }

            @Override
            public void onEnd() {
                super.onEnd();
                refreshLayout.refreshComplete();
                refreshLayout.loadMoreComplete();
            }
        });
    }

    @Override
    public void onColumnClick(LookBackBean fProgram) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (null != recyclerView) {
                    RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
                    View lastView = manager.findViewByPosition(lastPlayIndex);
                    if (null != lastView) {
                        LookBackNewsHolder lastHolder = (LookBackNewsHolder) recyclerView.getChildViewHolder(lastView);
                        lastHolder.pauseVideo();
                    }
                    if (null != playPlayer) {
                        playPlayer.onVideoPause();
                    }
                }
            }
        }, 200);
        //点击选择栏目
        Intent intent = new Intent(this, LookBackNewsDetailActivity.class);
        intent.putExtra(LookBackNewsDetailActivity.COLUMN_ID, fProgram.getProgrammeId());
        intent.putExtra(LookBackNewsDetailActivity.COLUMN_NAME, fProgram.getProgrammeName());
        intent.putExtra(LookBackNewsDetailActivity.COLUMN_URL,  fProgram.getProgrammeDate());
        startActivity(intent);
    }

    //记录当前准备播放的数据
    private LookBackNewsHolder willHolder;
    private int index;

    @Override
    public void OnItemClick(FProgram item, int position) {
        if (lastPlayIndex == position) {
            RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
            View lastView = manager.findViewByPosition(lastPlayIndex);
            if (null != lastView && recyclerView.getChildViewHolder(lastView) instanceof LookBackNewsHolder) {
                LookBackNewsHolder lastHolder = (LookBackNewsHolder) recyclerView.getChildViewHolder(lastView);
                willHolder = lastHolder;
                index = position;
                    String id = lastHolder.exchangeStatus(adapter.isMute());
//            initPlayer(lastHolder.getVideoPlayer());
                    lastPlayIndex = position;
                    if (!TextUtils.isEmpty(id)) {
                        //播放，增加点击量
                        initViewClickData(id);
                }

            }
            return;
        }
        JLog.e("OnItemClick", " position = " + position);
        isNotScrolled = true;
        isNotScrollStateChanged = true;
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        View lastView = manager.findViewByPosition(lastPlayIndex);
        if (null != lastView && recyclerView.getChildViewHolder(lastView) instanceof LookBackNewsHolder) {
            LookBackNewsHolder lastHolder = (LookBackNewsHolder) recyclerView.getChildViewHolder(lastView);
            lastHolder.pauseVideo();
        }
        if (position < adapter.getItemCount()) {
            if (position != -1) {
                smoothMoveToPosition(recyclerView, position);
            } else {
                smoothMoveToPosition(recyclerView, position + 1);
            }
        }
//        recyclerView.scrollToPosition(position);

        View view = manager.findViewByPosition(position);

        if (null != view && recyclerView.getChildViewHolder(view) instanceof LookBackNewsHolder) {
            LookBackNewsHolder lastHolder = (LookBackNewsHolder) recyclerView.getChildViewHolder(view);
            willHolder = lastHolder;
            index = position;
                String id = lastHolder.playVideo(adapter.isMute());
//            initPlayer(lastHolder.getVideoPlayer());
                lastPlayIndex = position;
                if (!TextUtils.isEmpty(id)) {
                    //播放，增加点击量
                    initViewClickData(id);
                }
        }
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                isNotScrolled = false;
                isNotScrollStateChanged = false;
            }
        }, 500);
    }

    @Override
    public void OnItemInit(BasePlayerView player, int position) {
        initPlayer(player, position);
    }

    /**
     * 初始化播放控件，以实现全屏等功能
     *
     * @param player
     * @param index
     */
    private void initPlayer(BasePlayerView player, int index) {
        if (lookBackList.size() > index) {
            playPlayer = player;
            VideoInfo videoInfo = new VideoInfo("");
            videoInfo.Cdn = "cdn";
            videoInfo.VideoOriginalName = lookBackList.get(index).getProgrammeName();
            videoInfo.VideoName = lookBackList.get(index).getProgrammeName();
            videoInfo.VideoUrl = Constances.ST_BASE_URL + lookBackList.get(index).getProgram().getProgrammeUrl();
            videoInfo.extendProperty1 = "直播三台APP_Android";
            videoInfo.extendProperty1 = "";
            videoInfo.extendProperty1 = NetUtils.GetNetName(this);
            videoInfo.setVideoWebChannel("///");
            if (null != player) {
                initVideoPlayer(player, videoInfo, videoInfo.VideoUrl.endsWith("m3u8"), this);
            }
        }
    }

    private boolean isNormalScreenShow = true;

    @Override
    public void onFullClick(boolean isNormal) {
        isNormalScreenShow = isNormal;
    }

    @Override
    public void onBackPressed() {
        if (isNormalScreenShow) {
//            isCanPlayVideo = false;

            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (null != recyclerView) {
                        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
                        View lastView = manager.findViewByPosition(lastPlayIndex);
                        if (null != lastView) {
                            LookBackNewsHolder lastHolder = (LookBackNewsHolder) recyclerView.getChildViewHolder(lastView);
                            lastHolder.pauseVideo();
                            lastHolder.releaseVideo();
                        }
                        if (null != playPlayer) {
                            playPlayer.onVideoPause();
                            playPlayer.release();
                        }
                    }
                    LookBackNewsActivity.super.onBackPressed();
                }
            }, 200);
        } else {
            super.onBackPressed();
        }
    }



    /**
     * 记录点击
     *
     * @param programId
     */
    private void initViewClickData(String programId) {
        SkipUtil.skipToAddUserOperate( this, getOwnerName(), 9, 7, "节目回看", programId, Cache.getInstance().getCurrentChannelId());
    }

    /**
     * 滑动到指定位置
     */
    private void smoothMoveToPosition(RecyclerView mRecyclerView, final int position) {
        JLog.e("OnItemClick---", "smoothMoveToPosition  position = " + position);
        // 第一个可见位置
        int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0));
        // 最后一个可见位置
        int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1));
        if (position < firstItem) {
            // 第一种可能:跳转位置在第一个可见位置之前
            mRecyclerView.smoothScrollToPosition(position);
        } else if (position <= lastItem) {
            // 第二种可能:跳转位置在第一个可见位置之后
            int movePosition = position - firstItem;
            if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) {
                int top = mRecyclerView.getChildAt(movePosition).getTop();
                mRecyclerView.smoothScrollBy(0, top);
            }
        } else {
            // 第三种可能:跳转位置在最后可见项之后
            mRecyclerView.smoothScrollToPosition(position);
            mToPosition = position;
            mShouldScroll = true;
        }
    }

    @OnClick(value = {R.id.title_top_layout_back})
    public void topClick(View view) {
        switch (view.getId()) {
            case R.id.title_top_layout_back:
                finish();
                break;

        }
    }

    @Override
    protected void onDestroy() {
        if(null!= willHolder){
            willHolder.pauseVideo();
            willHolder.releaseVideo();
        JLog.e("VideoPlayer---", "onDestroy");
        }
        super.onDestroy();
    }


}
